// controllers/article_controller.go
package controllers

import (
	"strconv"

	"gorm_project/services"
	"gorm_project/utils"

	"github.com/gin-gonic/gin"
)

type ArticleController struct {
	articleService *services.ArticleService
}

func NewArticleController(articleService *services.ArticleService) *ArticleController {
	return &ArticleController{
		articleService: articleService,
	}
}

func (ctrl *ArticleController) GetArticles(c *gin.Context) {
	articles, err := ctrl.articleService.GetPublishedArticles()
	if err != nil {
		utils.InternalError(c, "获取文章列表失败")
		return
	}

	utils.Success(c, articles)
}

func (ctrl *ArticleController) GetArticle(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		utils.BadRequest(c, "文章ID格式错误")
		return
	}

	article, err := ctrl.articleService.GetArticleByID(uint(id))
	if err != nil {
		utils.NotFound(c, "文章不存在")
		return
	}

	utils.Success(c, article)
}

func (ctrl *ArticleController) CreateArticle(c *gin.Context) {
	var req services.CreateArticleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.BadRequest(c, "请求参数错误")
		return
	}

	userID := utils.GetUserIDFromContext(c)
	article, err := ctrl.articleService.CreateArticle(req, userID)
	if err != nil {
		utils.InternalError(c, "创建文章失败")
		return
	}

	utils.Success(c, article)
}
